<template>
  <div class="register">
    <!-- 表单 -->
    <van-form @submit="onSubmit">
     

      <van-field v-model="account" name="account" label="账号" placeholder="请输入" />

      <van-field v-model="nickName" name="nickName" label="昵称" placeholder="请输入" />

      <van-field v-model="email" name="email" label="邮箱" placeholder="请输入" />

      <van-field v-model="password" type="password" name="upass" label="密码" placeholder="请输入" />

      <van-field v-model="password2" type="password" name="upass2" label="确认密码" placeholder="请输入" />

      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit">立即注册</van-button>
      </div>

      <div>
        <router-link class="link" to="/login">已账号，马上登录?</router-link>
      </div>
    </van-form>
    <!--使用组件 跳转首页 -->
    <back-to></back-to>
  </div>
</template>

<script>
// 导入组件
import BackTo from '@/components/BackTo.vue'
import { Toast, Dialog } from 'vant'
import { register } from '../api/index'

export default {
  data() {
    return {
      nickName: '',
      account: '',
      email: '',
      password: '',
      password2: ''
    };
  },
  // 注册组件
  components: {
    BackTo
  },
  methods: {

    // 点击“注册”的业务逻辑
    async onSubmit(values) {
      console.log('submit', values);
      // 解构赋值
      let { nickName, upass, upass2 , account, email} = values;
      // 判断输入框是否为空
      if (nickName === "" || nickName == "" || upass == "" || upass2 == "" || email == "") {
        // 弹窗提示
        // Toast.fail('输入框不能为空');
        Toast('输入框不能为空~');
        return false;
      }
      if (upass.length < 6) {
          Toast('密码需要6位字符以上')
          return false
        }

        if (upass != upass2) {
          Toast.fail('两次输入的密码不一致')
          return false
        }


       await  register({nickName, account, password: upass, email}).then(
          content=>{
            console.log(content)
            let {code , msg } = content;
            if(code == 200) {
               // 给用户反馈“注册结果”
                Dialog.alert({
                  confirmButtonColor: "#0c8bf3",
                  message: '注册成功，跳转登录。',
                }).then(() => {
                  // on close
                  // 跳转登录页
                  this.$router.push({ path: '/login' })
                });
            }
            else {
              Toast(msg);
            }
          }
        ).catch(err=>console.log(err))

    },
  },
};
</script>

<style lang="less">
@import '../common/less/varible.less';

.register {
  padding-top: 150px;

  .van-button--normal {
    background-color: @bgColor;
    border: 0;
  }

  .link {
    display: block;
    width: 100%;
    text-align: center;
    font-size: 16px;
    // text-decoration: underline;

  }
}
</style>
